package com.ashlikun.okhttputils.http.extend

import okhttp3.MultipartBody
import okhttp3.Request
import okio.Buffer
import java.io.IOException
import java.nio.charset.Charset

/**
 * 作者　　: 李坤
 * 创建时间: 2024/10/31　15:26
 * 邮箱　　：496546144@qq.com
 *
 * 功能介绍：请求相关扩展
 */

/**
 * 修改请求参数里面的某个字段
 */
fun Request.setRequestParams(data: Map<String, Any>, isAdd: Boolean = true): Request.Builder {
    val builder = newBuilder()
    if (isAdd) {
        if ("GET" == method) url.newBuilder().setUrlParams(data, isAdd)
    } else {
        url.newBuilder().setUrlParams(data, isAdd)
    }
    builder.method(method, body?.setParams(data, isAdd))
    return builder
}

/**
 * 修改请求参数里面的某个字段
 * 这个返回的对象不是入参时候的对象
 */
fun Request.Builder.setRequestParams(data: Map<String, Any>, isAdd: Boolean = true) = build().setRequestParams(data, isAdd)


/**
 * 获取 request 整个数据
 */
fun Request.getRequestToString(): String {
    val request = this
    val sb = StringBuilder()
    sb.append("Url   : " + request.url.toUrl().toString())
    sb.append("\nMethod: ${request.method}")
    sb.append("\nHeads : ")
    sb.append(request.headers.toStringNoSensitive())
    sb.append("\nRequestBody : ")
    val requestBody = request.body
    if (requestBody != null) {
        if (request.body is MultipartBody) {
            (request.body as MultipartBody).parts.forEach {
                val headers = it.headers
                val disposition = headers?.get("Content-Disposition")
                if (disposition != null) {
                    val isFile = disposition!!.contains("filename")
                    // 打印非文件部分
                    sb.append("Content-Disposition: $disposition\n")
                    sb.append("Content-Type: ${headers?.get("Content-Type")}\n")
                    sb.append("Content-Length: ${it.body.contentLength()}\n")
                    val name = disposition.substringAfter("name=\"").substringBefore("\"")
                    if (!isFile) {
                        val bufferedSink = Buffer()
                        it.body.writeTo(bufferedSink)
                        val value = bufferedSink.readString(
                            requestBody.contentType()?.charset() ?: Charset.forName("utf-8")
                        )
                        sb.append("$name: $value\n")
                    } else {
                        val fileName = disposition.substringAfter("filename=\"").substringBefore("\"")
                        sb.append("$fileName =  $fileName\n")
                    }
                    sb.append("\n")
                }
            }
            return sb.toString()
        } else {
            try {
                val bufferedSink = Buffer()
                requestBody.writeTo(bufferedSink)
                sb.append("\n")
                sb.append(
                    bufferedSink.readString(
                        requestBody.contentType()?.charset() ?: Charset.forName("utf-8")
                    )
                )
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }

    }
    return sb.toString()
}
